import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts';
import { useSize } from 'ahooks';
// @ts-ignore
import { getCssVariableValue } from '@/utils/utils';
import { useThemeChange } from '@/hooks/useThemeChange';

const QuantityPriceCharts: React.FC<IQuantityPriceChartsProps> = (props) => {
  const { data = {}, filters = {}, dimensionKeys = [], stations = {}, tableColumns = [] } = props;
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstanceRef = useRef<echarts.ECharts | null>(null);
  const chartSize = useSize(chartRef);
  const { theme } = useThemeChange();

  useEffect(() => {
    if (chartRef.current) {
      chartInstanceRef.current = echarts.init(chartRef.current);
    }

    return () => {
      chartInstanceRef.current?.dispose();
    };
  }, []);

  useEffect(() => {
    if (!chartSize?.width) return;
    chartInstanceRef.current?.resize();
  }, [chartSize]);

  useEffect(() => {
    if (chartInstanceRef.current) {
      let series = [],
        xAxisData = [];
      const legendData = ['差额电量', '日前结算电价', '基数电价'];

      const newDimensionKeys = dimensionKeys.slice(0, -1);
      const childNameList = {};
      let lastData = {};
      newDimensionKeys.forEach((val, ind) => {
        let lastName = filters?.[val] || '';
        if (val === 'stationName') {
          lastName = stations?.[filters?.[val]]?.label || '';
        } else if (val === 'date') {
          lastName = filters?.[val].format('YYYY-MM-DD');
        }
        childNameList[ind + 1] = lastName;
      });
      if (Object.values(childNameList)?.length === 4)
        lastData =
          data?.[childNameList[1]]?.[childNameList[2]]?.[childNameList[3]]?.[childNameList[4]] ||
          {};
      if (Object.values(childNameList)?.length === 3)
        lastData = data?.[childNameList[1]]?.[childNameList[2]]?.[childNameList[3]] || {};
      if (Object.values(childNameList)?.length === 2)
        lastData = data?.[childNameList[1]]?.[childNameList[2]] || {};
      if (Object.values(childNameList)?.length === 1) lastData = data?.[childNameList[1]] || {};
      // console.log(data)
      // console.log(childNameList)
      // console.log(lastData)
      delete lastData.data;
      delete lastData.order;
      xAxisData = Object.keys(lastData).sort();
      let data1Index = 1,
        data2Index = 1;
      const data1 = [],
        data2 = [],
        data3 = [];
      tableColumns.forEach((tKey, tInd) => {
        if (tKey.field === 'balancePower') {
          data1Index = tInd;
        }
        if (tKey.field === 'dayAheadSettlementPrice') {
          data2Index = tInd;
        }
      });
      xAxisData.forEach((xKey) => {
        if (lastData[xKey].data?.length) {
          data1.push(lastData[xKey].data?.[data1Index] || null);
          data2.push(lastData[xKey].data?.[data2Index] || null);
          data3.push(332);
        }
      });

      series = [
        {
          name: '差额电量',
          type: 'bar',
          data: data1,
        },
        {
          name: '日前结算电价',
          type: 'line',
          yAxisIndex: 1,
          data: data2,
        },
        {
          name: '基数电价',
          type: 'line',
          yAxisIndex: 1,
          data: data3,
        },
      ];

      const option: echarts.EChartsOption | any = {
        grid: {
          top: '11%',
          left: '5%',
          right: '5%',
          bottom: '6%',
          containLabel: true,
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: '#161A1D', // 设置背景颜色为黑色
          textStyle: {
            fontSize: 14,
            lineHeight: 14,
            color: '#A7A8A9',
          },
          borderWidth: 0,
          axisPointer: {
            type: 'line',
            lineStyle: { width: 1, color: '#4E5154', type: 'solid' },
          },
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          axisPointer: {
            type: 'line',
            lineStyle: {
              type: 'solid',
              color: getCssVariableValue('--chart-x-line'),
            },
          },
          axisLine: {
            show: true,
            onZero: false,
            lineStyle: {
              type: 'solid',
              color: getCssVariableValue('--chart-x-line'),
            },
          },
          axisTick: {
            alignWithLabel: true,
            lineStyle: {
              color: getCssVariableValue('--chart-x-line'),
            },
          },
          axisLabel: {
            textStyle: {
              color: (value: string) => {
                return props.chartsIsMaintained?.indexOf(value) > -1
                  ? getCssVariableValue('--font-primary')
                  : getCssVariableValue('--chart-font-color');
              },
            },
            fontSize: 12,
            // interval: 0,
            rotate: 45,
          },
        },
        yAxis: [
          {
            type: 'value',
            name: 'MWh',
            axisTick: {
              alignWithLabel: true,
              length: 4,
              lineStyle: {
                color: getCssVariableValue('--chart-y-line'),
              },
            },
            axisLabel: {
              color: getCssVariableValue('--chart-font-color'),
              fontSize: 12,
            },
            splitLine: {
              show: true,
              lineStyle: {
                type: 'solid',
                color: getCssVariableValue('--chart-y-line'),
              },
            },
          },
          {
            type: 'value',
            name: '元/MWh',
            axisTick: {
              alignWithLabel: true,
              length: 4,
              lineStyle: {
                color: getCssVariableValue('--chart-y-line'),
              },
            },
            axisLabel: {
              color: getCssVariableValue('--chart-font-color'),
              fontSize: 12,
            },
            splitLine: {
              show: true,
              lineStyle: {
                type: 'solid',
                color: getCssVariableValue('--chart-y-line'),
              },
            },
          },
        ],
        legend: {
          data: legendData,
          bottom: 0, // 放置在底部
          left: 'center', // 水平居中
          textStyle: {
            color: getCssVariableValue('--chart-legend-color'),
          },
          icon: 'circle',
          type: 'scroll', // 可选，支持滚动的图例
          itemHeight: 10, //圆点大小
          itemWidth: 10, // 线的长度
          pageIconColor: getCssVariableValue('--bd-primary'),
          pageTextStyle: {
            color: getCssVariableValue('--chart-legend-color'),
          },
        },
        series: series,
      };

      chartInstanceRef.current.setOption(option, true);
    }
  }, [props.data, filters, theme]);

  return <div ref={chartRef} className="quantity-price-charts" />;
};

interface IQuantityPriceChartsProps {
  xAxisData: any[];
  chartsDataObj?: Record<string, any>;
  // chartsIsMaintained: string[];
}

export default QuantityPriceCharts;
